assert(PandaDKPMaster, "PandaDKPMaster not found!")

------------------------------
--      Are you local?      --
------------------------------
local PandaDKPMaster = PandaDKPMaster
local Items =
{
   UI = {},
}
PandaDKPMaster.Items = Items

local dewdrop = AceLibrary("Dewdrop-2.5")
local dewOptions = {}


function Items:Enable()
   Items:SetupUI()
end


function Items:GetDKP(itemId)
   itemId = tostring(itemId)
   
   local dkp = 0
   local pool = nil
   
   if (nil ~= PandaDKPMaster.db.realm.DKP.Items[itemId]) then
      dkp = PandaDKPMaster.db.realm.DKP.Items[itemId].dkp
      pool = PandaDKPMaster.db.realm.DKP.Items[itemId].pool
   end
   
   return dkp, pool
end

function Items:ShouldIncludeItem(itemId)
   itemId = tostring(itemId)
   
   -- If item is in auto skip list, then return false
   
   -- If item is in DKP list, return true
   if (nil ~= PandaDKPMaster.db.realm.DKP.Items[itemId]) then return true end
   
   -- If item adding and meets threshold, return true
   if (PandaDKPMaster.db.realm.ItemAdding) then
      local _, _, quality = GetItemInfo(itemId)
      if (quality >= PandaDKPMaster.db.realm.ItemQuality) then return true end
   end
   
   return false
end

function Items:IsAutoBank(itemId)
   return false
end


-- Use this when we're the ones setting the DKP through the interface
function Items:InternalSetDKP(itemId, dkp, pool)
   itemId = tostring(itemId)
   dkp = tonumber(dkp)
   
   -- Get the item's info
   local name, _, _, _, _, type, subtype = GetItemInfo(itemId)
   if (nil == name) then PandaDKPMaster:Print(string.format("Could not retrive info for item %d", itemId)) return end
   
   -- Set the database value
   local ts = PandaDKPMaster:GetTimestamp()
   PandaDKPMaster.Events:InsertSetItemEvent(ts, itemId, dkp, pool, type, subtype, name)
   
   -- Send a message to the guild
   local message = PandaDKPMaster.Messages:CreateSIMessage(ts, itemId, dkp, pool, type, subtype, name)
   PandaDKPMaster.Comm:Send("GUILD", message)
end


-- Called when a SI message is seen
function Items:OnSetItemMessage(timestamp, itemId, dkp, pool, type, subtype, name)
   -- MD5 the message
   local message = PandaDKPMaster.Messages:CreateSIMessage(timestamp, itemId, dkp, pool, type, subtype, name)
   local md5 = PandaDKPMaster.MD5Lib:MD5(message)
   
   -- If we've already seen it, skip it
   if (nil ~= PandaDKPMaster.db.realm.DKP.Events[md5]) then return end
   
   -- Add the event
   PandaDKPMaster.Events:InsertSetItemEvent(timestamp, itemId, dkp, pool, type, subtype, name)
end


-- Used internally to set an item's value. You chould generally not use this function. Instead use
-- InternalSetDKP or OnSetItemMessage
function Items:SetItemValue(itemId, dkp, pool, type, subtype, name)
   local item =
   {
      itemId = itemId,
      dkp = dkp,
      pool = pool,
      name = name,
      type = type,
      subtype = subtype
   }
   PandaDKPMaster.db.realm.DKP.Items[itemId] = item
end












----------------------
--   Interface UI   --
----------------------

function Items:SetupUI()
   Items.UI.SortOrder = { "name", "pool", "dkp" }
   
   PDKPM_ItemsConfigListLinkHeaderTitle:SetText("Item")
   PDKPM_ItemsConfigListLinkHeader.sorter = "name"
   PDKPM_ItemsConfigListPoolHeaderTitle:SetText("Pool")
   PDKPM_ItemsConfigListPoolHeader.sorter = "pool"
   PDKPM_ItemsConfigListDKPHeaderTitle:SetText("DKP")
   PDKPM_ItemsConfigListDKPHeader.sorter = "dkp"
   
   PDKPM_ItemEditPoolButton:SetScript("OnClick",
    function()
      PandaDKPMaster.Items:PoolListClicked(PDKPM_ItemEditPool)
      PlaySound("igMainMenuOptionCheckBoxOn");
	 end)
   
   Items:RefilterList()
end


function Items:ConfigPanelOnShow()
   Items:RefilterList()
end

function Items:ConfigPanelOnHide()
end

function Items:OnItemClick(self, button, id)
   -- If its a ctrl-click, then show the item in dress up
   if (button == "LeftButton" and IsControlKeyDown()) then
      DressUpItemLink(Items.UI.List[id].link)
      return
   elseif (button == "LeftButton" and IsShiftKeyDown()) then
      ChatEdit_InsertLink(Items.UI.List[id].link)
      return
   end
end

function Items:ItemListOnClick(self, button, id)
   dewOptions = { type = "group", args = {} }
	
	dewOptions.args.edit = { type = 'execute', name = 'Edit Item...', order = 1, desc = 'Edit the item',
	 func = function(id) PandaDKPMaster.Items:EditItem(id) end, passValue = id }
   
   dewdrop:Open(self, 'children', dewOptions, 'point', "TOP", 'relativePoint', "TOP")
end

function Items:ShowTooltip(button, id)
   GameTooltip:SetOwner(button, "ANCHOR_TOPLEFT")
   GameTooltip:SetHyperlink(Items.UI.List[id].link)
   local dkp, pool = PandaDKPMaster.Items:GetDKP(Items.UI.List[id].itemId)
   GameTooltip:AddLine(" ")
   GameTooltip:AddDoubleLine(string.format("DKP = %0.2f", dkp), pool, 1.0, 0.819, 0.0, 1.0, 0.819, 0.0)
   GameTooltip:Show()
   if IsShiftKeyDown() then GameTooltip_ShowCompareItem() end
   CursorUpdate()
end

function Items:RefilterList()
   Items.UI.List = {}
   
   -- Add a record for every item that meets the filter
   for itemId, itemRec in pairs(PandaDKPMaster.db.realm.DKP.Items) do
      local name, link, _, _, _, type, subtype, _, _, texture = GetItemInfo(itemId)
      if (nil == link) then
         GameTooltip:SetHyperlink("item:"..itemId..":0:0:0:0:0:0:0")
         name, link, _, _, _, type, subtype, _, _, texture = GetItemInfo(itemId)
      end
      local record =
      {
         itemId = itemId,
         name = itemRec.name,
         link = link,
         tex = texture,
         pool = itemRec.pool,
         dkp = itemRec.dkp,
      }
      tinsert(Items.UI.List, record)
   end
   
   -- Sort the list according to the sort order
   local function SortList(a, b)
      if (a[Items.UI.SortOrder[1]] == b[Items.UI.SortOrder[1]]) then
         if (a[Items.UI.SortOrder[2]] == b[Items.UI.SortOrder[2]]) then
            return a[Items.UI.SortOrder[3]] < b[Items.UI.SortOrder[3]]
         else
            return a[Items.UI.SortOrder[2]] < b[Items.UI.SortOrder[2]]
         end
      else
         return a[Items.UI.SortOrder[1]] < b[Items.UI.SortOrder[1]]
      end
   end
   sort(Items.UI.List, SortList)
   
   Items:ListUpdate()
end



function Items:ListUpdate()
   local numEntries = #(Items.UI.List)
   FauxScrollFrame_Update(PDKPM_ItemsConfigListScrollFrame, numEntries, 19, 19, nil, 350, 350, nil, 350, 350, true)
   
   local line
   local offset
   
   for line = 1, 19 do
      offset = line + FauxScrollFrame_GetOffset(PDKPM_ItemsConfigListScrollFrame)
      local button = _G["PDKPM_ItemsConfigListLine"..line]
      button:SetID(offset)
      if (offset <= numEntries) then
      
         local text = _G["PDKPM_ItemsConfigListLine"..line.."Link"]
         text:SetText(Items.UI.List[offset].link)
         
         text = _G["PDKPM_ItemsConfigListLine"..line.."Pool"]
         text:SetText(Items.UI.List[offset].pool)
         
         text = _G["PDKPM_ItemsConfigListLine"..line.."DKP"]
         text:SetText(string.format("%.2f", Items.UI.List[offset].dkp))
         
         text = _G["PDKPM_ItemsConfigListLine"..line.."Item"]
         text:SetNormalTexture(Items.UI.List[offset].tex)
         
         button:Show()
      else
         button:Hide()
      end
   end
   
end


function Items:HeaderOnClick(header, button)
   local newSort = { header.sorter }
   
   for i, sort in pairs(Items.UI.SortOrder) do
      if (sort ~= header.sorter) then tinsert(newSort, sort) end
   end
   
   Items.UI.SortOrder = newSort
   Items:RefilterList()
end


function Items:EditItem(id)
   PDKPM_ItemEdit.itemId = Items.UI.List[id].itemId
   PDKPM_ItemEditLootLink:SetText(Items.UI.List[id].link)
   PDKPM_ItemEditLootButton:SetNormalTexture(Items.UI.List[id].tex)
   PDKPM_ItemEditLootButton.link = Items.UI.List[id].link
   PDKPM_ItemEditPoolText:SetText(Items.UI.List[id].pool)
   PDKPM_ItemEditDkp:SetText(Items.UI.List[id].dkp)
   
   PDKPM_ItemEdit:Show()
   dewdrop:Close();
end


function Items:EditItemOkayClicked()
   Items:InternalSetDKP(PDKPM_ItemEdit.itemId, PDKPM_ItemEditDkp:GetText(), PDKPM_ItemEditPoolText:GetText())
   PDKPM_ItemEdit:Hide()
   Items:RefilterList()
end

function Items:PoolListClicked(button)
   local options = { type = "group", args = {}, }
   for i, pool in ipairs(PandaDKPMaster.db.realm.DKP.Pools) do
      local option =
      {
         type = 'execute',
         name = pool,
         desc = pool,
         func = function(pool) PDKPM_ItemEditPoolText:SetText(pool) dewdrop:Close(); end,
         order = i,
         passValue = pool,
      }
      tinsert(options.args, option)
   end
   dewdrop:Open(button, 'children', options, 'point', "TOP", 'relativePoint', "BOTTOM")
end